package com.suez.nullpointerexception.blizzard.cserver;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

import com.suez.nullpointerexception.blizzard.controller.AController;
import com.suez.nullpointerexception.blizzard.controller.AddController;
import com.suez.nullpointerexception.blizzard.controller.DelController;
import com.suez.nullpointerexception.blizzard.controller.LsController;
import com.suez.nullpointerexception.blizzard.controller.QController;
import com.suez.nullpointerexception.blizzard.controller.UpdateController;
import com.suez.nullpointerexception.blizzard.global.Global;


public class CServer {
	ServerSocket ss;
	OutputStream os;
	Socket socket1 ;
	public void start() throws IOException{
		ss = new ServerSocket(5555);
		init();
		Global.logMsg="on";
		Global.serDate = new Date();
		System.out.println("Blizzard Server Started...");
		try {
			while(true){
				socket1 = ss.accept();//阻塞语句
				os = socket1.getOutputStream();				
				os.write((Global.logMsg+"\n").getBytes("utf-8"));
				new Thread(new ClientRunnable(socket1)).start();				
			}
		}catch(Exception e){
			System.err.println("Server Stopped...");
			//e.printStackTrace();
		}
	}
	
	public void stop(){
		
		Global.logMsg="off";
		//System.exit(0);
		try {
			Global.userMsg.clear();
			if(Global.socketPool.size()!=0){
				for(int i =0;i<Global.socketPool.size();i++)
				{
					socket1 = Global.socketPool.get(i);
					ObjectOutputStream oos = new ObjectOutputStream(Global.socketPool.get(i).getOutputStream());
					oos.writeObject("off");				
				}
				Global.socketPool.clear();
				//socket1.close();
			}
			ss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//System.err.println("Server Stopped...");
			e.printStackTrace();
		}		
	}
	
	private static void init(){
		AController addController = new AddController();
		AController updateController = new UpdateController();
		AController delController = new DelController();
		AController lsController = new LsController();
		AController qController = new QController();
		
		Global.controllers.put("A",addController);
		Global.controllers.put("U",updateController);
		Global.controllers.put("D",delController);
		Global.controllers.put("L",lsController);
		Global.controllers.put("Q",qController);
	}
	
}
